﻿using AutoMapper;
using Consul;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Reporting.API.Application.Commands.RBAC.Users;
using Reporting.API.DTOs.RBAC;
using Reporting.Domain.RBAC;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.RBAC.Permissions;
using Reporting.Infrastructure.Interfaces.RBAC.RolePermissionss;
using Reporting.Infrastructure.Interfaces.RBAC.Roles;
using Reporting.Infrastructure.Interfaces.RBAC.UserRoles;
using Reporting.Infrastructure.Interfaces.RBAC.Users;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Reporting.API.Application.CommandHandler.RBAC.Users
{
    public class LoginUserCommandHandler : IRequestHandler<LoginUserCommand, ApiResult<UserRepository>>
    {
        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IPermissionRepository _permissionRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRolePermissionsRepository _rolePermissionsRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<LoginUserCommandHandler> _logger;
        private readonly IConfiguration _configuration; // 配置接口，用于读取应用程序配置(JWT读取登录用户)

        public LoginUserCommandHandler(ILogger<LoginUserCommandHandler> logger, IMapper mapper, IUserRepository userRepository, IRoleRepository roleRepository, IPermissionRepository permissionRepository, IUserRoleRepository userRoleRepository, IRolePermissionsRepository rolePermissionsRepository, IConfiguration configuration)
        {
            _logger = logger;
            _mapper = mapper;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _permissionRepository = permissionRepository;
            _userRoleRepository = userRoleRepository;
            _rolePermissionsRepository = rolePermissionsRepository;
            _configuration = configuration;
        }

        public async Task<ApiResult<UserRepository>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取用户信息
                var users = await _userRepository.GetAsync(x => x.UserName == request.UserName && x.Password == request.Password);
                if (users == null)
                {
                    return ApiResult<UserRepository>.Fail("用户名或密码错误", StatusCodeEnum.Unauthorized);
                }

                if (users.IsDel == false)
                {
                    return ApiResult<UserRepository>.Fail("该账号已被禁用", StatusCodeEnum.Unauthorized);
                }
                ////
                //var role = await _roleRepository.GetAllAsync();
                ////
                //var permissions = await _permissionRepository.GetAllAsync();
                ////
                //var userRoles = await _userRoleRepository.GetAllAsync();
                ////
                //var rolePermissionss = await _rolePermissionsRepository.GetAllAsync();

              


                // 手动赋值
                var result = new UserRepository
                {
                    UserId = users.UserId,
                    UserName = users.UserName,
                    Password = users.Password,
                    NickName = users.NickName,
                    IsDel = users.IsDel,
                    RoleIdtostring = users.RoleIdtostring ,// 如果 RoleIdtostring 为空，则自动为 null
                    Token=GenerateJwtToken(users.UserId, users.UserName)
                };

                // 返回成功结果
                return ApiResult<UserRepository>.Success(result, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<UserRepository>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }

        /// <summary>
        /// 生成JWT Token的方法，用于用户认证。
        /// </summary>
        /// <param name="UserId">用户Id</param>
        /// <param name="UserName">用户名称</param>
        /// <returns>返回生成的JWT Token字符串</returns>
        private string GenerateJwtToken(int UserId, string UserName)
        {
            // 定义用户声明
            var claims = new[]
            {
                new Claim("UserId", UserId.ToString()), // 用户id
                new Claim("UserName", UserName) // 用户名称
            };

            // 签名密钥和凭证
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]));
            var creeds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // 创建JWT Token
            var token = new JwtSecurityToken(
                _configuration["Authentication:Issuer"], // 发行者
                _configuration["Authentication:Audience"], // 受众
                claims, // 用户声明
                expires: DateTime.Now.AddHours(8), // 过期时间
                signingCredentials: creeds // 签名凭证
            );

            // 返回序列化的JWT Token字符串
            return new JwtSecurityTokenHandler().WriteToken(token);
        }



    }
}
